{% extends "base.html" %}

{% block title %}用户登录{% endblock %}

{% block content %}
<div class="auth-container fade-in">
    <div class="text-center mb-4">
        <div class="auth-icon">
            <i class="fas fa-sign-in-alt"></i>
        </div>
        <h2 class="mb-2">用户登录</h2>
        <p class="text-muted">请输入您的账号信息</p>

        <!-- 登录状态提示 -->
        <div id="login-alert" class="alert alert-danger" role="alert"></div>
    </div>

    <form id="loginForm">
        <div class="mb-3">
            <label for="username" class="form-label fw-bold">
                <i class="fas fa-user me-2"></i>用户名
            </label>
            <input type="text" class="form-control" id="username" required
                   placeholder="请输入用户名" autocomplete="username">
        </div>
        <div class="mb-3">
            <label for="password" class="form-label fw-bold">
                <i class="fas fa-lock me-2"></i>密码
            </label>
            <input type="password" class="form-control" id="password" required
                   placeholder="请输入密码" autocomplete="current-password">
        </div>
        
        <div class="remember-me">
            <input type="checkbox" id="remember" name="remember">
            <label for="remember">记住我</label>
        </div>

        <button type="submit" class="btn btn-primary w-100 btn-login">
            <i class="fas fa-sign-in-alt me-2"></i>登录
        </button>

        <div class="text-center mt-3">
            <a href="{{ url_for('auth.forgot_password') }}" class="text-decoration-none text-muted">忘记密码?</a>
            <span class="mx-2 text-muted">|</span>
            <a href="{{ url_for('auth.register') }}" class="text-decoration-none text-primary">注册新账号</a>
        </div>
    </form>
</div>

<style>
.auth-container {
    max-width: 450px;
    margin: 5rem auto;
    padding: 3rem;
    background: white;
    border-radius: 16px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
    transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.auth-container:hover {
    box-shadow: 0 15px 40px rgba(0,0,0,0.15);
}

.auth-icon {
    width: 80px;
    height: 80px;
    margin: 0 auto 1.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(135deg, var(--primary-color), var(--accent-color));
    color: white;
    border-radius: 50%;
    font-size: 2rem;
}

.form-control {
    padding: 0.75rem 1.25rem;
    border-radius: 12px;
    border: 1px solid rgba(0,0,0,0.1);
    transition: all 0.3s ease;
}

.form-control:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 0.25rem rgba(67, 97, 238, 0.25);
}

.btn-login {
    padding: 0.75rem;
    border-radius: 12px;
    font-weight: 600;
    letter-spacing: 0.5px;
    transition: all 0.2s ease;
}

.btn-login:hover {
    transform: translateY(-2px);
}

.btn-login:active {
    transform: translateY(0);
}

#login-alert {
    border-radius: 12px;
    border: none;
    box-shadow: 0 5px 15px rgba(0,0,0,0.05);
    opacity: 0;
    transform: translateY(-10px);
    transition: all 0.3s ease;
}

#login-alert.show {
    opacity: 1;
    transform: translateY(0);
}

.remember-me {
    display: flex;
    align-items: center;
    margin-bottom: 1.5rem;
}

.remember-me input {
    margin-right: 0.5rem;
}

/* 响应式调整 */
@media (max-width: 576px) {
    .auth-container {
        padding: 2rem 1.5rem;
        margin: 3rem auto;
    }
    
    .auth-icon {
        width: 70px;
        height: 70px;
        font-size: 1.75rem;
    }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const loginForm = document.getElementById('loginForm');
    const alertBox = document.getElementById('login-alert');

    // 自动填充测试账号（仅开发环境）
    if (window.location.hostname === 'localhost') {
        document.getElementById('username').value = 'testuser';
        document.getElementById('password').value = 'testpass123';
    }

    // 登录表单处理
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        try {
            const response = await fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: new URLSearchParams({ username, password })
            });

            const data = await response.json();

            if (data.success) {
                // 存储认证信息
                localStorage.setItem('userId', data.user.id);
                localStorage.setItem('sessionToken', data.session_token);

                // 执行状态验证
                await verifyAuthStatus();

                // 处理重定向逻辑
                const redirectUrl = new URLSearchParams(window.location.search).get('redirect');
                window.location.href = redirectUrl || '/';
            } else {
                showAlert(data.message || '认证失败，请检查用户名和密码');
            }
        } catch (error) {
            console.error('登录错误:', error);
            showAlert('服务器连接异常，请稍后重试');
        }
    });

    // 显示错误提示
function showAlert(message) {
    alertBox.textContent = message;
    alertBox.classList.add('show');
    setTimeout(() => alertBox.classList.remove('show'), 3000);
}

    // 验证认证状态
    async function verifyAuthStatus() {
        try {
            const response = await fetch('/api/check_auth', {
                headers: {
                    'Authorization': `Bearer ${localStorage.getItem('sessionToken')}`
                }
            });

            if (!response.ok) {
                localStorage.clear();
                window.location.reload();
            }
        } catch (error) {
            console.error('状态验证失败:', error);
            showAlert('会话验证异常');
        }
    }

    // 初始状态检查
    (async function init() {
        if (localStorage.getItem('sessionToken')) {
            await verifyAuthStatus();
        }
    })();
});
</script>
{% endblock %}
